package org.jeecg.util;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.jeecgframework.p3.core.util.HttpUtils;
import org.springframework.stereotype.Component;

import java.util.HashMap;

@Component
public class WeiBoUtil {



    public static String  authorize(String clientId){
        HashMap<String,String> paramMap = new HashMap<>();
        paramMap.put("client_id","client_id");
        paramMap.put("client_secret","client_secret");
        paramMap.put("grant_type","authorization_code");

        String result = HttpUtils.post("https://api.weibo.com/oauth2/authorize", paramMap);
        JSONObject jsonObject = JSON.parseObject(result);
        return  jsonObject.getString("access_token");
    }

    public static String  getAccessToken(){
        HashMap<String,String> paramMap = new HashMap<>();
//        paramMap.put("client_id",clientId);
//        paramMap.put("client_secret",clientSecret);
//        paramMap.put("grant_type",code);

        String result = HttpUtils.post("https://api.weibo.com/oauth2/access_token", paramMap);
        JSONObject jsonObject = JSON.parseObject(result);
        return  jsonObject.getString("access_token");
    }

    public static String  getAccessToken(String clientId,String clientSecret,String code){
        HashMap<String,String> paramMap = new HashMap<>();
        paramMap.put("client_id",clientId);
        paramMap.put("client_secret",clientSecret);
        paramMap.put("grant_type",code);

        String result = HttpUtils.post("https://api.weibo.com/oauth2/access_token", paramMap);
        JSONObject jsonObject = JSON.parseObject(result);
        return  jsonObject.getString("access_token");
    }


    /**
     * 获取微博用户信息
     * @param id
     * https://open.weibo.com/wiki/2/users/show
     * @return
     */
    public JSONObject getUserInfo(String id,String clientId,String clientSecret,String code){
        String weiBoToken = WeiBoUtil.getAccessToken(clientId,clientSecret,code);
        String url = "https://api.weibo.com/2/users/show.json?access_token="+weiBoToken+"uid="+id;
        String s = HttpUtil.get(url);
        return  JSONObject.parseObject(s);
    }


    /**
     * 获取单条微博信息
     * @param id
     * https://open.weibo.com/wiki/2/statuses/show
    reposts_count	int	转发数
    comments_count	int	评论数
    attitudes_count	int	表态数
     * @return
     */
    public JSONObject getWeiBOSendInfo(String id){
        String weiBoToken = WeiBoUtil.getAccessToken();
        String url = "https://open.weibo.com/wiki/2/statuses/show"+weiBoToken+"id="+id;
        String s = HttpUtil.get(url);
        return  JSONObject.parseObject(s);
    }
}
